import React from "react";
import MenuStyle from  "./menu.scss";
import { Link, withRouter } from 'react-router-dom';
import { Menu, Modal, Select, message } from 'antd'
// import MenuData from '../../utils/menuData'
import cookie from 'react-cookies'
import {getMenu,getUserMenu} from '../../api/accountManage'
import store from '../../redux/store';

const { SubMenu } = Menu;
const { confirm } = Modal;
const { Option } = Select;


export class Sider extends React.Component {
	constructor(props, context) {
		super(props, context)
		this.state = {
            is_subaccount:false,
			menu_list:[],
			openKeys: ['0'],
			current: ['0'],
			pathSnippetds: null,
			exrtraBreadcrumbItems: null,
            name:''
		}
	}
	componentWillReceiveProps(){
		//页面切换时展开选项设置为切换后当前选项。
        this.getPath();
	}
	componentWillUnmount() {
        const { is_subaccount } = this.state;
        if (is_subaccount){
            Modal.destroyAll();
        }
    }
    componentDidMount(){
        if (!cookie.load('station_console_setting_web_login')){
            message.error('登录失效！', 2, () => {
                this.props.history.push({ pathname: `/login` })
            })
            return;
        }
        this.setState({
            name:store.getState().addRole,
        })
        let post_data = {
            auth_token:cookie.load('station_console_setting_web_login').auth_token
        }
        getUserMenu(post_data).then(res => {
            let _this = this;
            const menu_list = res.data;
           // const index = menu_list.findIndex(item => item.index_menu === '0');//通过查找左边菜单所在位置排序，要求菜单按原型顺序返回。
            // menu_list.splice(0, index) 
            this.setState({
                menu_list
            }, () => {
                _this.getPath()
               
            })

        })
        // MenuData.data().then(data => {
        //     let _this = this;
        //     const menu_list = data;
        //     this.setState({
        //         menu_list
        //     }, () => {
        //         // _this.getPath()
               
        //     })
        // })
      
        
        
        // this.chkHasAuth();
    }
    //退出登录
    // doLogout = () => {
    //     cookie.remove('station_console_setting_web_login');
    //     window.location.href = process.env.RES_URL + '/ybhz?do=logout';
    // }
    //设置当前页面菜单展开与选中，以及是否显示三级菜单
    getPath = e => {
        const pathSnippets = window.location.pathname.split('/').filter(i => i);
        const { menu_list } = this.state;
        this.setState({
            openKeys: ['0'],
            current: ['0']
        })
       // console.log(pathSnippets)
        menu_list.forEach((item, i) => {
            if (!item.children){
                const url = pathSnippets[1] + '/' + pathSnippets[2]
                if (item.menu_url === url) {
                    this.setState({
                        openKeys: [item.id],
                        current: [item.id],
                    })
                }
                return;
            }
            item.children.forEach((el, ind) => {
                const url = pathSnippets[1] + '/' + pathSnippets[2]
                if (el.menu_url === url) {
                    this.setState({
                        openKeys: [item.id],
                        current: [el.id] 
                    })
                }
            })
        })
        
    }
	onOpenChange = openKeys => {
    //    console.log('openKeys',openKeys)
        const { menu_list } = this.state;
        const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
        // console.log(latestOpenKey,'latestOpenKey');
        const openIndex = menu_list.findIndex(item => item.id === latestOpenKey)
        // console.log(openIndex)
        if (openIndex === -1) {
			console.log('收起')
			this.setState({ 
				openKeys
			});
		} else {
			console.log('展开')
			this.setState({
				openKeys: latestOpenKey ? [latestOpenKey] : [],
				// current: ['21']
            });
            const openLink = menu_list[openIndex].children ? menu_list[openIndex].children[0].menu_url : menu_list[openIndex].menu_url;
            
			const openId = menu_list[openIndex].children ? menu_list[openIndex].children[0].id : menu_list[openIndex].id;
			// console.log(openLink,openId)
            /** 在子组件中，使用高阶组件withRouter，提供history，否则this.props.history为undefined **/
            this.props.history.push({pathname:`/index/${openLink}`,query:{id:openId}})
            this.getPath()
            
		}
	};
	onClick = (item, key, keyPath, domEvent) => {
		// console.log(item, key, keyPath, domEvent)
		this.setState({
			current: [item.key]
		},);
		
    }
    companyChange = e => {
        console.log(e)
    }

    doLogout = () => {
        cookie.remove('station_console_setting_web_login');
        sessionStorage.removeItem('urlConfig');
        this.props.history.push({ pathname: `/login` })
    }

  	render() {
        const { menu_list , name } = this.state;
    	return (
			<div className={MenuStyle.nav} id="navMain" style={{height:'100%'}}>
                <div className="menu_sel_company">
                    <div className="imgs">
                        <img src={require("../../assets/img/logoo.png")} alt="" />
                    </div>
                </div>
				<Menu mode = "inline"
                    className = "innernav"
					openKeys = { this.state.openKeys }
					selectedKeys={ this.state.current }
					onOpenChange = { this.onOpenChange }
					onClick = { this.onClick } >
                    {menu_list.map((el,i) => 
                       {
                        if (el.children&&el.children!==[]) {
                            return (
                                <SubMenu
                                    key={el.id}
                                    title={<span >
                                            <span className={`menuOne ${el.icon_url}`}></span>
                                            <span>{el.menu_name}</span> 
                                        </span>}
                                >
                                    {
                                        el.children.map((item, index) => (
                                            <Menu.Item key={item.id}>
                                                <Link to={
                                                {pathname:`/index/${item.menu_url}`,query:{id:item.id}}
                                                } > {item.menu_name} </Link>
                                            </Menu.Item>
                                        ))
                                    }
                                </SubMenu>
                            )
                        } else {
                            return (
                                <Menu.Item key={el.id}>
                                    <span style={{display:'inline-block',width:'16px',height:'16px'}} className={`menuOne2 ${el.icon_url}`}></span>
                                    <Link to={ {pathname:`/index/${el.menu_url}`,query:{id:el.id}} } > {el.menu_name} </Link>
                                </Menu.Item>
                            )
                        }
                    })}
				</Menu>
                <div className='username'>
                    <div className="userbox">
                        <img alt="" src={require('../../assets/img/undraw_Add_tasks_re_s5yj.png')}/>
                        <p>欢迎回来, {name}</p>
                        <p>Have a nice day</p>
                    </div>
                </div>
                <div className="logout" >
                    <span onClick={this.doLogout}><a>退出登录</a></span>
                </div>
            </div>
		)
    }
}

export default withRouter(Sider);